package cn.hxz.controller;

import cn.hxz.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;

/**
 * @Description: TODO
 * @Author: huangxinzhang
 * @Date: 2024/9/12
 **/
@Controller
public class UserController {

    /**
     * 向登录页面跳转
     */
    @RequestMapping(value = "/toLogin", method = RequestMethod.GET)
    public String toLogin() {
        System.out.println("toLogin......");
        return "login";
    }

    /**
     * 用户登录
     * @param user
     * @param model
     * @param httpSession
     * @return
     */
    @RequestMapping(value = "/loginUser", method = RequestMethod.POST)
    public String login(User user, Model model, HttpSession httpSession) {
        String username = user.getUsername();
        String password = user.getPassword();

        //模拟从数据库中获取用户名和密码进行判断
        if (username != null && username.equals("admin") && password != null && password.equals("123456")) {
            httpSession.setAttribute("user_session", user);
            //用户存在保存到session中，并复位到主页
            return "redirect:teacher";
        }
        //用户不存在，添加错误信息到model中，并跳转到登录页面
        model.addAttribute("msg", "用户或密码错误，请重新输入!");
        return "login";
    }

    /**
     * 向管理主页跳转
     * @return
     */
    @RequestMapping(value = "/main" , method = RequestMethod.GET)
    public String toMain() {
        System.out.println("toMain......");
        return "teacher";
    }
    /**
     * 退出
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:toLogin";
    }
}
